<template>
    <div>
        <HeaderNav />
        <div style="max-width:1200px;margin:auto;">
            <!--路径-->
            <div class="box">
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>购物车列表</el-breadcrumb-item>
                </el-breadcrumb>
            </div>

            <div v-if="!showData">购物车还没加入商品，<router-link to="/product/list"> 快去购物吧</router-link></div>
            <div v-else>
                <div style="text-align:left;">
                    <el-button @click="eventDelete('')" size="medium" type="danger">批量删除</el-button>
                </div>

                <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55">
                    </el-table-column>
                    <el-table-column label="店铺名称" width="120">
                        <template slot-scope="scope">{{ scope.row.storeName }}</template>
                    </el-table-column>
                    <el-table-column label="图片" width="120">
                        <template slot-scope="scope">{{ scope.row.date }}</template>
                    </el-table-column>
                    <el-table-column label="商品名称">
                        <template slot-scope="scope">
                            {{ scope.row.productName }}
                            <span v-if="scope.row.stockError == true"
                                style="color:red;font-size:24px;font-weight:600;">库存不足</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="productPrice" label="商品价格" width="120">
                        <template slot-scope="scope">
                            <span style="color:red;font-weight:600;">{{ (scope.row.productPrice).toFixed(2) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="productNumber" label="购买数量" width="180">
                        <template slot-scope="scope">
                            <el-input-number size="mini" v-model="scope.row.productNumber" @change="eventUpdate(scope.row)"
                                :min="1" :max="10000" label="描述文字"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="小计" width="120">
                        <template slot-scope="scope">
                            <span style="color:red;font-weight:600;">{{ (scope.row.productNumber *
                                scope.row.productPrice).toFixed(2)
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template slot-scope="scope">
                            <el-button size="mini" type="danger" @click="eventDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                应付总金额：<span style="color:red;font-size:30px;font-weight:600;">￥{{ total }}</span>
                <el-button @click="eventToSettle">立即结算</el-button>
            </div>
        </div>
    </div>
</template>
  
<script>
import HeaderNav from '@/components/HeaderNav.vue'
export default {
    components: {
        //将这个组件在页面中，当作标签来使用即可
        HeaderNav
    },
    data() {
        return {
            tableData: [
                {
                    "productId": "8a43697d-b615-4d3a-8040-6190368a611c",
                    "productPrice": 75,
                    "productNumber": 2,
                    "productName": "台式电脑测试数据",
                    "productImage": "",
                    "productSpec": "",
                    "stockError": true,
                    "storeName": '店铺1'
                },
                {
                    "productId": "9c023df9-62e9-4d0e-bf2f-19fbb240d1a4",
                    "productPrice": 85,
                    "productNumber": 1,
                    "productName": "好用实惠真不贵",
                    "productImage": "",
                    "productSpec": "",
                    "stockError": false,
                    "storeName": '店铺2'
                },
                {
                    "productId": "8c023df9-62e9-4d0e-bf2f-19fbb240d1a4",
                    "productPrice": 95,
                    "productNumber": 2,
                    "productName": "好用实惠真不贵ppppppppp",
                    "productImage": "",
                    "productSpec": "",
                    "stockError": false,
                    "storeName": '店铺2'
                }
            ],
            multipleSelection: [],
            userId: '',
            showData: false
        }
    },
    mounted() {
        //获取登录用户的信息（在登录的时候，就将登录的用户信息放入到本地缓存了，所以这个时候可以直接取）
        let userInfo = localStorage.getItem('2010a_login_info')
        if (userInfo == null) {
            this.$router.push('/member/login')
        }
        //这个时候，userInfo是json字符串，我们直接点不出来。需要将json字符串转换为json对象
        this.userId = JSON.parse(userInfo).id
        this.onLoadData()
    },
    computed: {
        total() {
            let sum = 0
            this.multipleSelection.forEach(x => {
                sum += x.productNumber * x.productPrice
            })
            //运费（不满100，需要另付8元运费
            if (sum > 0 && sum < 100) {
                sum += 8
            }
            return sum.toFixed(2)
        }
    },
    methods: {
        //跳转到结算页面
        eventToSettle() {

            //要传的数据在哪里？ this.multipleSelection
            if (this.multipleSelection.length <= 0) {
                this.$message.error('请选择需要结算的商品')
            } else {
                //this.$router.push('/product/settle')
                this.$router.push({ name: 'product/settle', params: { data: this.multipleSelection } })
            }
        },
        //修改购物车商品数量
        eventUpdate(row) {
            let url = this.$baseUrl + '/car'
            let data = {
                "key": this.userId,
                "values": []
            }
            data.values.push(row)
            this.$http.put(url, data).then(res => {
                console.log(res)
            })
        },

        // //批量删除数据
        // eventDeleteAll() {
        //     let url = this.$baseUrl + '/car'
        //     let data = {
        //         "key": this.userId,
        //         "values": []
        //     }
        //     data.values = this.multipleSelection
        //     this.$http.delete(url, { data: data }).then(res => {
        //         console.log(res)
        //     })
        // },

        //删除一条数据
        eventDelete(row) {
            let url = this.$baseUrl + '/car'
            let data = {
                "key": this.userId,
                "values": []
            }
            if (row == '') {
                if (this.multipleSelection.length <= 0) {
                    this.$message.error('请选择需要删除的商品')
                    return
                }
                data.values = this.multipleSelection
            } else {
                data.values.push(row)
            }



            this.$confirm('确认要删除这些商品吗？此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.delete(url, { data: data }).then(res => {
                    console.log(res)
                    if (res.data.code == 200) {
                        this.onLoadData()
                    }
                })
                    .catch(err => {
                        console.log(err)
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });



        },
        //加载购物车中的数据
        onLoadData() {
            let url = this.$baseUrl + '/car'
            this.$http.get(url, {
                params: {
                    key: this.userId
                }
            }).then(res => {
                if (res.data.code == 200) {
                    console.log(res)
                    this.tableData = res.data.data
                    this.showData = true
                }
                else {
                    this.showData = false
                }
            })
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        }
    }
}
</script>